/**
 * 
 */
package com.google.code.sip.ucenter.security;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.google.code.sip.ucenter.model.Role;
import com.google.code.sip.ucenter.model.User;
import com.google.code.sip.ucenter.service.UserManager;
import com.google.code.sip.ucenter.utils.StringRegexUtils;
import com.google.common.collect.Sets;

/**
 * @author Liuye
 * 
 */
public class UserDetailServiceImpl implements UserDetailsService {
	@Autowired
	private UserManager userManager;

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		User user = null;
		if (StringRegexUtils.isEmail(username)) {
			user = userManager.getUserByEmail(username);
		} else {
			user = userManager.getUserByName(username);
		}
		if (user == null)
			throw new UsernameNotFoundException(username + " 不存在");

		Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(user);

		// 目前User类中没有credentialsNonExpired,accountNonLocked属性，所以设为true.
		boolean enabled = user.isEnabled();
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = !user.isLocked();

		UserDetails userdetails = new org.springframework.security.core.userdetails.User(
				user.getUsername(), user.getPassword(), enabled,
				accountNonExpired, credentialsNonExpired, accountNonLocked,
				grantedAuths);

		return userdetails;
	}

	/**
	 * 获得用户所有角色的权限集合.
	 */
	private Set<GrantedAuthority> obtainGrantedAuthorities(User user) {
		Set<GrantedAuthority> authSet = Sets.newHashSet();
		Role role = user.getRole();
		if (role != null) {
			authSet.add(new GrantedAuthorityImpl(role.getPrefixedName()));
		}
		return authSet;
	}

}
